import { AuthActionTypes, LOGIN_TYPE, SESSION_LOGIN, LOGOUT, LOGOUT_WEB } from './types'
import { Dispatch } from 'redux'
import { post, get } from '../../ajax/axios'
import { Api, Admin } from '../../ajax/api'
import Cookie from 'js-cookie'
import { PublicENV } from '@config/env'

/**
 * 获取CSRF
 */
export function getCsrf() {
  get(Api.csrf)
}

/**
 * 登录
 * @param user 用户名
 * @param pass 密码
 * @param code 验证码
 */
export function loginAction(user: string, pass: string, code: string): (dispatch: Dispatch<AuthActionTypes>) => Promise<AuthActionTypes> {
  return (dispatch: Dispatch<AuthActionTypes>) => {
    return new Promise((res, rej) => {
      post(Api.user.login, {
        user, pass, code
      }).then((data: any) => {
        Cookie.set(PublicENV.ADMIN_LOGIN, 'true')
        dispatch({
          type: LOGIN_TYPE,
          value: data
        })
        res()
      }).catch((err) => {
        rej(err)
      })
    })
  }
}

/**
 * session 登录
 */
export function sessionLoginAction(data: any): any {
  return (dispatch: Dispatch<AuthActionTypes>) => {
    // cookie
    const cookie = data.ctx.req.headers.cookie
    console.log('cookie = ', cookie)
    if (cookie && cookie.indexOf(PublicENV.ADMIN_LOGIN) >= 0) {
      return new Promise((res, rej) => {
        get(Api.user.sessionLogin, {}, {
          headers: {
            cookie
          }
        }).then((data: any) => {
          if (data) {
            dispatch({
              type: SESSION_LOGIN,
              value: data
            })
          }
          res(data)
        }).catch((err) => {
          rej(err)
        })
      })
    }
  }
}

/**
 * 退出登录
 */
export function logout(): (dispatch: Dispatch<AuthActionTypes>) => Promise<AuthActionTypes> {
  return (dispatch: Dispatch<AuthActionTypes>) => {
    return new Promise((res, rej) => {
      get(Admin.auth.user.logout).then((data: any) => {
        dispatch({
          type: LOGOUT,
        })
        Cookie.remove(PublicENV.ADMIN_LOGIN)
        res(data)
      }).catch((err) => {
        rej(err)
      })
    })
  }
}

/**
 * 前端退出登录
 */
export function logout_web(): (dispatch: Dispatch<AuthActionTypes>) => void {
  return (dispatch: Dispatch<AuthActionTypes>) => {
    dispatch({
      type: LOGOUT_WEB,
    })
  }
}



